/**
 * 简化版调试网络客户端 - 专注HTTP通信，稳定可靠
 *
 * 使用方式：
 * 1. 复制此文件到您的项目中
 * 2. 修改 serverUrl 为您的调试面板地址
 * 3. 在App中导入: import './utils/debugClient-simple'
 * 4. 使用: global.$debug.info('Hello World')
 *
 * 特点：
 * - 纯HTTP通信，不使用WebSocket
 * - 零依赖（不需要axios）
 * - 自动重试机制
 * - 专门解决连接超时问题
 */

class SimpleDebugClient {
  constructor(config = {}) {
    this.config = {
      serverUrl: 'http://10.240.20.130:3000', // 修改为您的调试面板IP地址
      enabled: typeof __DEV__ !== 'undefined' ? __DEV__ : true, // 开发环境启用
      timeout: 8000, // 请求超时时间
      retryCount: 2, // 重试次数
      retryDelay: 1000, // 重试延迟
      ...config,
    }

    this._timers = new Map()
    this._requestId = 0

    if (this.config.enabled) {
      console.log('🚀 SimpleDebugClient initialized:', this.config.serverUrl)
      this._testConnection()
    }
  }

  /**
   * 生成唯一请求ID
   */
  _generateRequestId() {
    return Date.now() + '_' + ++this._requestId
  }

  /**
   * 发送HTTP请求（带重试机制）
   */
  async _sendHTTP(data, retryCount = 0) {
    if (!this.config.enabled) return false

    const requestId = this._generateRequestId()

    try {
      console.log(`📡 [${requestId}] Sending ${data.type} log...`)

      const controller = new AbortController()
      const timeoutId = setTimeout(() => controller.abort(), this.config.timeout)

      const response = await fetch(`${this.config.serverUrl}/api/log`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
        signal: controller.signal,
      })

      clearTimeout(timeoutId)

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }

      console.log(`✅ [${requestId}] Log sent successfully`)
      return true
    } catch (error) {
      const errorMsg = error.name === 'AbortError' ? 'Request timeout' : error.message

      // 重试机制
      if (retryCount < this.config.retryCount) {
        console.warn(`⚠️ [${requestId}] Send failed (${retryCount + 1}/${this.config.retryCount + 1}): ${errorMsg}, retrying...`)

        // 延迟重试
        await new Promise((resolve) => setTimeout(resolve, this.config.retryDelay * (retryCount + 1)))
        return this._sendHTTP(data, retryCount + 1)
      } else {
        console.warn(`❌ [${requestId}] Send failed after ${this.config.retryCount + 1} attempts: ${errorMsg}`)
        return false
      }
    }
  }

  /**
   * 发送日志到远程调试面板
   */
  async _sendLog(level, messages) {
    if (!this.config.enabled) return

    const logData = {
      type: 'log',
      timestamp: Date.now().toString(),
      data: {
        id: this._generateRequestId(),
        timestamp: Date.now().toString(),
        level,
        message: messages.map((msg) => {
          if (typeof msg === 'object') {
            try {
              return JSON.stringify(msg, null, 2)
            } catch (e) {
              return String(msg)
            }
          }
          return String(msg)
        }),
        environment: this._getEnvironment(),
        userAgent: this._getUserAgent(),
      },
    }

    return await this._sendHTTP(logData)
  }

  /**
   * 获取运行环境
   */
  _getEnvironment() {
    if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
      return 'React Native'
    }
    if (typeof window !== 'undefined') {
      return 'Browser'
    }
    if (typeof process !== 'undefined' && process.versions && process.versions.node) {
      return 'Node.js'
    }
    return 'Unknown'
  }

  /**
   * 获取用户代理
   */
  _getUserAgent() {
    if (typeof navigator !== 'undefined') {
      return navigator.userAgent || 'Unknown'
    }
    return 'Unknown'
  }

  /**
   * 测试连接
   */
  async _testConnection() {
    console.log('🔍 Testing connection to debug server...')

    const success = await this._sendLog('info', ['🔗 SimpleDebugClient connection test'])

    if (success) {
      console.log('✅ Debug server connection successful')
    } else {
      console.warn('❌ Debug server connection failed')
      console.log('💡 Please check:')
      console.log('  1. Server is running: npm run server:status')
      console.log('  2. Server URL is correct:', this.config.serverUrl)
      console.log('  3. Network connectivity')
    }
  }

  // ==================== 基础日志方法 ====================

  debug(...messages) {
    return this._sendLog('debug', messages)
  }

  info(...messages) {
    return this._sendLog('info', messages)
  }

  log(...messages) {
    return this._sendLog('log', messages)
  }

  warn(...messages) {
    return this._sendLog('warn', messages)
  }

  error(...messages) {
    return this._sendLog('error', messages)
  }

  // ==================== 业务场景方法 ====================

  userAction(action, details = {}) {
    return this.info(`👤 ${action}`, {
      type: 'user_action',
      action,
      details,
      timestamp: new Date().toISOString(),
    })
  }

  pageEvent(page, event, extra = {}) {
    return this.info(`📱 ${page} - ${event}`, {
      type: 'page_event',
      page,
      event,
      extra,
      timestamp: new Date().toISOString(),
    })
  }

  networkLog(method, url, requestData = null, responseData = null, duration = 0) {
    return this.info(`🌐 ${method.toUpperCase()} ${url}`, {
      type: 'network',
      method: method.toUpperCase(),
      url,
      requestData,
      responseData,
      duration,
      timestamp: new Date().toISOString(),
    })
  }

  errorLog(error, context = '') {
    return this.error(`❌ ${context}`, {
      type: 'error_log',
      message: error.message,
      stack: error.stack,
      context,
      timestamp: new Date().toISOString(),
    })
  }

  performanceLog(operation, duration, details = {}) {
    return this.info(`⚡ ${operation} (${duration}ms)`, {
      type: 'performance',
      operation,
      duration,
      details,
      timestamp: new Date().toISOString(),
    })
  }

  // ==================== 高级功能 ====================

  table(data, title = 'Table Data') {
    return this.info(`📊 ${title}`, {
      type: 'table',
      data,
      title,
      timestamp: new Date().toISOString(),
    })
  }

  time(label) {
    this._timers.set(label, Date.now())
    return this.debug(`⏱️ Timer '${label}' started`)
  }

  timeEnd(label) {
    const startTime = this._timers.get(label)

    if (startTime) {
      const duration = Date.now() - startTime
      this._timers.delete(label)
      return this.info(`⏱️ Timer '${label}': ${duration}ms`, {
        type: 'timer',
        label,
        duration,
        timestamp: new Date().toISOString(),
      })
    } else {
      return this.warn(`⏱️ Timer '${label}' does not exist`)
    }
  }

  async clear() {
    const clearData = {
      type: 'clear',
      timestamp: Date.now().toString(),
      data: { action: 'clear' },
    }

    const success = await this._sendHTTP(clearData)

    if (success) {
      console.log('🧹 Remote logs cleared')
    } else {
      console.warn('📡 Clear logs failed')
    }

    return success
  }

  async testConnection() {
    console.log('🔍 Testing debug connection...')
    const success = await this._sendLog('info', ['🔗 Manual connection test'])

    if (success) {
      console.log('✅ Debug connection test successful')
    } else {
      console.warn('❌ Debug connection test failed')
    }

    return success
  }

  updateConfig(newConfig) {
    this.config = { ...this.config, ...newConfig }
    console.log('🔧 SimpleDebugClient config updated:', this.config)
  }

  getStatus() {
    return {
      enabled: this.config.enabled,
      serverUrl: this.config.serverUrl,
      connectionType: 'HTTP',
      environment: this._getEnvironment(),
      userAgent: this._getUserAgent(),
      timeout: this.config.timeout,
      retryCount: this.config.retryCount,
    }
  }
}

// 创建全局实例
const $debug = new SimpleDebugClient()

// 挂载到全局
if (typeof global !== 'undefined') {
  global.$debug = $debug
} else if (typeof window !== 'undefined') {
  window.$debug = $debug
}

// 导出
if (typeof module !== 'undefined' && module.exports) {
  module.exports = $debug
}

// 初始化测试（延迟一点让其他日志先输出）
if ($debug.config.enabled) {
  setTimeout(() => {
    $debug.info('🚀 SimpleDebugClient ready', {
      environment: $debug._getEnvironment(),
      serverUrl: $debug.config.serverUrl,
      status: $debug.getStatus(),
    })
  }, 500)
}

